﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Web.SessionState;
using Newtonsoft.Json;
using Framework.DataAccess;
using Framework.Common.JsonEntities;
using Framework.Common;
using Framework.Common.Common;
using Mode;
namespace WebSite.WebServer
{
    /// <summary>
    /// UserManage 的摘要说明
    /// </summary>
    public class UserManage : IHttpHandler, IRequiresSessionState
    {
        JsonReturnMessages msg;
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            msg = new JsonReturnMessages();
            try
            {
                if (context.Request.Params["Action"] == "Login")
                    Login();
                if (context.Request.Params["Action"] == "AreaList")
                    GetTheAreaListJson();
                if (context.Request.Params["Action"] == "Department")
                    GetTheDepartmentListJson();
                if (context.Request.Params["Action"] == "Reg")
                    Reg();
                if (context.Request.Params["Action"] == "EditPaswd")
                    EditPaswd();

                //if (context.Request.Params["Action"] == "GetRole")
                //    GetRole();
            }
            catch (Exception err)
            {
                var message = err.Message;
                if (err.InnerException != null && err.InnerException.Message != null)
                    message += "<BR>" + err.InnerException.Message;
               
                msg.IsSuccess = 0;
                msg.Msg = message;

                var json = JsonConvert.SerializeObject(msg);
                context.Response.Write(json);
            }
            context.Response.End();
        }

        void Login()
        {
            var context = System.Web.HttpContext.Current;
            string ph = context.Request.Params["ph"].ToStr();
            string pwd = context.Request.Params["pwd"].ToStr();
            User u = new User();
            loginInfo uf=new loginInfo();
            u.login(ph, pwd, out uf);
            if (uf != null)
            {
                if (uf.A_ID > 0)
                {

                    SessionShard.loginUser = uf;

                    //把对象放在全局对象中
                 

                    msg.IsSuccess = 1;
                    var dd = new { m_status = uf.M_STATUS };
                    msg.Data = dd;
                }
                else
                {
                    msg.IsSuccess = 0;
                    msg.Msg = "登陆信息不正确!";
                }
            }
            else
            {
                msg.IsSuccess = 0;
                msg.Msg = "登陆信息不正确!";
            }

            context.Response.Write(JsonConvert.SerializeObject(msg));
        }




        void Reg()
        {
            var context = System.Web.HttpContext.Current;
        
            RegInfo reg = new RegInfo();
            reg.username = context.Request.Params["user"].ToStr();
            reg.sex = context.Request.Params["sex"].ToStr();
            reg.tel = context.Request.Params["tel"].ToStr();
            reg.workcode = context.Request.Params["code"].ToStr();
            reg.department = context.Request.Params["bm"].ToStr();
            reg.email = context.Request.Params["email"].ToStr();
            reg.are = context.Request.Params["are"].ToStr();
            string[] mm = context.Request.Params["areid"].Split(';');
            if (mm.Length > 0)
                reg.areid = mm[mm.Length - 1];
            else
                reg.areid = "0";
            reg.zw = context.Request.Params["zw"].ToStr();
            reg.zwid = context.Request.Params["zwid"].ToInt();
            reg.pwd = context.Request.Params["pwd"].ToStr();

            if (reg.areid.ToInt() > 0 && reg.zwid > 0)
            {
                User u = new User();
                if (u.Reguser(reg) > 0)
                {
                    msg.IsSuccess = 1;
                }
                else
                {
                    msg.IsSuccess = 0;
                    msg.Msg = "数据提交失败！";
                }
            }
            else
            {
                msg.IsSuccess = 0;
                msg.Msg = "区域或职务没选择正确！";
            }

            context.Response.Write(JsonConvert.SerializeObject(msg));
        }




        /// <summary>
        /// 获得区域
        /// </summary>
        void GetTheAreaListJson()
        {

            var context = System.Web.HttpContext.Current;
            var nodes = new List<JsonTreeNode>();
            DataView dv = new User().GetTheAreaList();
             if(dv !=null){
              DataView dvparent =dv.ToTable().DefaultView;
                 dvparent.RowFilter="level=0";
                 if(dvparent[0] !=null){
                    
                  JsonTreeNode node = new JsonTreeNode();
                  node.id = dvparent[0]["id"].ToString();
                  node.text = dvparent[0]["name"].ToString();
              
                 

                  DataView dvch = dv.ToTable().DefaultView;
                  dvch.RowFilter = "level=1";
                  if (dvch != null)
                  {
                      for (int j = 0; j < dvch.Count; j++)
                      {
                          JsonTreeNodeCh cnode = new JsonTreeNodeCh();
                          cnode.id = dvch[j]["id"].ToString();
                          cnode.text = dvch[j]["name"].ToString();

                          node.children.Add(cnode);
                      }
                  }

                  nodes.Add(node);
               
                 
              }

             }
             context.Response.Write(JsonConvert.SerializeObject(nodes));
        }
        /// <summary>
        /// 获得职务
        /// </summary>
        void GetTheDepartmentListJson()
        {
            var context = System.Web.HttpContext.Current;
            string[] mm = context.Request.Params["areaid"].ToStr().Split(';');
            
            int areid = mm[mm.Length -1].ToInt();

            DataView dv = new User().GetTheDepartmentList(areid);
            List<JsonComboBox> items = new List<JsonComboBox>();
            if (dv != null)
            {
                for (int i = 0; i < dv.Count; i++)
                {
                    JsonComboBox dd = new JsonComboBox();
                    dd.id = dv[i]["id"].ToStr();
                    dd.text = dv[i]["name"].ToStr();

                    items.Add(dd);
                }
            }
            context.Response.Write(JsonConvert.SerializeObject(items));
        }

        void EditPaswd() {
            var context = System.Web.HttpContext.Current;
            int userid = context.Request.Params["id"].ToInt();
            string pwd = context.Request.Params["pwd"].ToString();
            loginInfo lu = chklogin();
            if (lu != null)
            {
                User u = new User();
                int rcount = u.UpdatePwd(userid, pwd);
                if (rcount > 0) {
                    msg.IsSuccess = 1;
                    msg.Msg = "";
                }
            }

            context.Response.Write(JsonConvert.SerializeObject(msg));
        }


        loginInfo chklogin()
        {
            try
            {
                return SessionShard.loginUser;
            }
            catch
            {
                msg.IsSuccess = -9;
                msg.Msg = "登陆失效，请重新登陆!";
                return null;
            }
        }
       
        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}